package org.jeecg.demo.wx.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * 功能描述
 * 小程序token工具类
 *
 * @author: zgq
 * @date: 2024年01月29日 11:35
 */
@Slf4j
public class WXJWTUtil {

    public static final long EXPIRE_TIME = 7 * 24 * 60 * 60;
    public static final String CLAIM_NAME = "openid";

    public static String sign(String openid, String sessionKey) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(sessionKey);
        return JWT.create().withClaim(CLAIM_NAME, openid).withExpiresAt(date).sign(algorithm);
    }

    public static boolean verify(String token, String openid, String sessionKey) {
        try {
            DecodedJWT decodedJWT = JWT.decode(token);
            // 检查 token 是否过期
            Date expiresAt = decodedJWT.getExpiresAt();
            if (expiresAt != null && expiresAt.before(new Date())) {
                log.warn("token 已过期");
                return false; // token 已过期
            }
            // 进行合法性验证
            Algorithm algorithm = Algorithm.HMAC256(sessionKey);
            JWTVerifier jwtVerifier = JWT.require(algorithm).withClaim(CLAIM_NAME, openid).build();
            jwtVerifier.verify(token);
            return true; // token 验证成功且未过期
        } catch (Exception e) {
            return false; // token 验证失败
        }
    }


    public static String getOpenid(String token) {
        try {
            DecodedJWT decodedJWT = JWT.decode(token);
            return decodedJWT.getClaim(CLAIM_NAME).asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    public static void main(String[] args) {
        String token = WXJWTUtil.sign("dawn", "zgq040229");
        boolean verify = WXJWTUtil.verify(token, "dawn", "zgq040229");
        String openid = WXJWTUtil.getOpenid(token);
        System.out.println("token = " + token);
        System.out.println("verify = " + verify);
        System.out.println("openid = " + openid);
    }

}
